import http from './interface'
import {
	decrypt
} from '../utils/aes.js'

//解密脱敏字段集合 type(姓名 1、手机号 2、身份证 3)
const tmList = [
	{prop:'card',type:3},
	{prop:'phone',type:2},
	{prop:'passengerName',type:1},
	{prop:'contactNum',type:2},
	{prop:'linkPerson',type:1},
	{prop:'linkPhone',type:2},
	{prop:'passName',type:1},
	{prop:'credentialNum',type:3},
	{prop:'phoneNum',type:2},
	{prop:'guestName',type:1},
	{prop:'guestPhone',type:2},
	{prop:'touristName',type:1},
	{prop:'touristCode',type:3},
	{prop:'touristPhone',type:2},
	{prop:'linkName',type:1},
	{prop:'linkMobile',type:2},
	{prop:'idCode',type:3},
	{prop:'complainantName',type:1},
	{prop:'complainantPhone',type:2},
	{prop:'idCard',type:3},
	{prop:'guestName',type:1},
	{prop:'guestPhone',type:2},
	{prop:'checkInName',type:1},
	{prop:'checkInPhone',type:2},
	{prop:'legalPerson',type:1},
	{prop:'operatorCard',type:3},
	{prop:'realName',type:1},
	{prop:'workName',type:1},
	// {prop:'landlinePhone',type:2},
	{prop:'childName',type:1}
];
// 不做脱敏处理的api集合(页面上需要单独处理的)
const apiList = [
	'/api/commonPerson/list',
	'/api/register/getSettledApplyInfo',
	'/api/isinvoiceheader/page',
	'/api/commrecruit/page',
	'/api/commjobhunt/page',
	'/api/commjobhunt/getOne',
	'/api/commvolunteer/page',
	'/api/merchant/food/page',
	'/api/merchant/food/merchant',
	'/api/hotel/getHomestayInfo',
	'/api/fishingappointment/details',
	'/api/tourShoot/followUp',
	'/api/tourShoot/searchStudio',
	'/api/house/page',
	'/api/complaint',
	'/sys/user/info',
	'/api/house/getOne',
	'/api/merchant/food/queryOrderDetail',
	'/api/fishering/personCenterOrderDetail',
	'/api/hotel/getHotelOrderInfo',
	'/api/commvolunteer/getOne',
	'/api/repast/getRepastOrderInfo',
	'/api/rankTop/queryList'
]

export const $http = (url, method, data, json, isAuth, isBuffer, isLoading) => {
	let authorization = uni.getStorageSync('authorization') ||
		'Basic cmluZ3psZTpyaW5nemxl'; //Basic cmVucmVuaW86cmVucmVuaW8=
	let access_token = uni.getStorageSync('access_token') || '';
	//设置请求前拦截器
	http.interceptor.request = (config) => {
		if(isLoading){
			uni.showLoading({
				title: '加载中...'
			})
		}
		config.header = {
			'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
			'access_token': access_token
		}
		if (isAuth){
			config.header.authorization = authorization;
		}else{
			config.header.authorization = 'Basic cmluZ3psZTpyaW5nemxl'
		} 
		if (isBuffer) config.responseType = 'arrayBuffer';
		if(uni.getStorageSync('userInfo')) config.header.yhauth = JSON.parse(uni.getStorageSync('userInfo')).openId
	}
	//设置请求结束后拦截器
	http.interceptor.response = async (response) => {
		//判断返回状态 执行相应操作
		if(isLoading){
			uni.hideLoading()
		}
		//数据解密脱敏处理
		if (response.data && response.data.data) {
			let t = apiList.find(a => url.indexOf(a) > -1);
			if (!t) dealJmTmData(response.data.data, true);
			else dealJmTmData(response.data.data, false);
		}

		if ((response.data && response.data.code && response.data.code === 401) ||
			(response.data && response.data.msg && (response.data.msg.indexOf('未授权') > -1 ||
				response.data.msg.indexOf('重新登录') > -1))) {
			let pages = getCurrentPages();
			let lastPage = pages[pages.length - 1];
			let content = "当前登录已失效，是否返回我的页面重新登录？";
			if (lastPage.$vm.$refs.phoneNumber) content = "当前登录已失效，是否重新进行授权登录？";
			return uni.showModal({
				title: '温馨提示',
				content,
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync('authorization');
						uni.removeStorageSync('access_token');
						uni.removeStorageSync('userInfo');
						uni.removeStorageSync('isLogin');
						if (lastPage.$vm.$refs.phoneNumber) return lastPage.$vm.$refs
							.phoneNumber.show = true;
						uni.reLaunch({
							url: '/pages/my/index'
						})
					}
				}
			})
		}
		// 请根据后端规定的状态码判定
		if (response.data.code === 300) { //token失效
			//	return response.data = await doRequest(response, url)//动态刷新token,并重新完成request请求
		} else {
			if (response.data.code == 10021 && response.data.msg) {
				uni.showToast({
					title: response.data.msg,
					icon: 'none',
					duration: 1500
				})
			}
		}

		return response;
	}
	return http.request({
		method: method,
		url: url,
		dataType: 'json',
		data,
	})
}

//解密脱敏处理
function dealJmTmData(data, isTm) {
	if (!data) return;
	let keys = Object.keys(data);
	keys.forEach(k => {
		let _t = tmList.find(t => t.prop == k);
		if (_t) {
			data[k] = data[k] ? (decrypt(data[k]) || data[k]) : '';
			if (isTm) data[k] = tmRules(data[k], _t.type);
		}

		if (typeof data[k] === 'object') {
			dealJmTmData(data[k], isTm);
		} else if (Array.isArray(data[k])) {
			data[k].forEach(dk => {
				if (typeof dk === 'object') {
					dealJmTmData(dk, isTm);
				}
			})
		}
	})
}

// 脱敏规则
function tmRules(value, type) {
	if (!value) return;
	let res = '';
	if (type == 1) {
		let arr = Array.from(value)
		if (arr.length === 2) {
			res = arr[0] + '*'
		} else if (arr.length > 2) {
			for (let i = 1; i < arr.length - 1; i++) {
				arr[i] = '*'
			}
			res = arr.join("")
		} else {
			res = value
		}
	} else if (type == 2) {
		res = value.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2");
	} else if (type == 3) {
		res = value.replace(/^(.{4})(?:\d+)(.{4})$/, "$1**********$2");
	}

	return res;
}

async function login() {
	return new Promise(resolve => {
		uni.login({
			provider: 'weixin',
			success(loginRes) {
				resolve(loginRes.code)
			},
			fail() {}
		});
	})
}

function postJson(url, data, json = true, isAuth = true, isBuffer = false, isLoading = true) {
	return $http(url, 'POST', data, json, isAuth, isBuffer, isLoading)
}

function get(url, data, json = true, isAuth = true, isBuffer = false, isLoading = true) {
	return $http(url, 'GET', data, json, isAuth, isBuffer, isLoading)
}

function post(url, data, json = true, isAuth = true, isBuffer = false, isLoading = true) {
	return $http(url, 'POST', data, json, isAuth, isBuffer, isLoading)
}

function put(url, data, json = true, isAuth = true, isBuffer = false, isLoading = true) {
	return $http(url, 'PUT', data, json, isAuth, isBuffer, isLoading)
}

function del(url, data, json = true, isAuth = true, isBuffer = false, isLoading = true) {
	return $http(url, 'DELETE', data, json, isAuth, isBuffer, isLoading)
}
function post2(url, data, json = true, isAuth = false, isBuffer = false, isLoading = true) {
	return $http(url, 'POST', data, json, isAuth, isBuffer, isLoading)
}
//检测文本和图像
import { BaseApi } from './baseApi.js';
const labelCfg = {
	10001:'含有广告内容',
	20001:'含有时政内容',
	20002:'含有色情内容',
	20003:'含有辱骂内容',
	20006:'含有违法犯罪内容',
	20008:'含有欺诈内容',
	20012:'含有低俗内容',
	20013:'含有版权内容',
	21000:'含有其他违规内容'
}
async function detectionContent(content,type=1){
	if(type==1){
		if(!uni.getStorageSync('userInfo')){
			return uni.showToast({
				title:'请先进行登录',
				icon:'none',
				duration:1500
			})
		}
		return new Promise((resolve,reject)=>{
			wx.request({
				method: 'POST',
				url:`${BaseApi}/api/app/wx/secCheckMsg`,
				dataType:'json',
				data:{
					content:encodeURIComponent(content),
					openId:JSON.parse(uni.getStorageSync('userInfo')).openId
				},
				success:res=>{
					let result = {};
					if(res.data.code===0){
						let errcode = res.data.data.errcode;
						result.code = errcode;
						
						if(errcode===0){
							let resu = res.data.data.result;
							if(resu.label===100){
								result.code = 0;
								result.msg = '系统繁忙,请稍后再试';
							}else{
								result.code = resu.label;
								result.msg = labelCfg[resu.label]||'含有其他违规内容';
							}
						}else{
							if(errcode==-1) result.msg = '系统繁忙,请稍后再试';
							else if(errcode==87014) result.msg = '内容包含敏感违规信息';
							else if(errcode==40003) result.msg = 'openid无效，请重新登录';
							else result.msg = '系统错误';
						}
					}
					return resolve(result)
				},
				fail: err => {
					return reject(err)
				}
			})
		})
	}else if(type==2){
		return new Promise((resolve,reject)=>{
			wx.uploadFile({
				method:'POST',
				url:`${BaseApi}/api/app/wx/secCheckImg`,
				filePath: content,
				name: 'file',
				header: {
					'Content-Type': 'application/octet-stream'
				},
				formData:{
					media:content
				},
				success: res => {
					let data = JSON.parse(res.data);
					let result = {code:999,msg:'数据错误'};
					if(data&&data.code===0){
						let resu = JSON.parse(data.data);
						if(!resu) return;
						result.code = resu.errcode;
						if(resu.errcode==87014) result.msg = '图片含有敏感违规信息';
						else if(resu.errcode==40001) result.msg = 'token无效';
						else if(resu.errcode==40003) result.msg = 'openid无效';
						else if(resu.errcode==61010) result.msg = '用户访问记录超时';
						else{
							result.code = 0;
							result.msg = '内容正常';
						}
					}
					return resolve(result)
				},
				fail: err => {
					return reject(err)
				}
			});
		})
	} 
}

export default {
	postJson,
	get,
	post,
	put,
	del,
	detectionContent,
	post2
}